<template>
  <div>
    <Button type="info" icon="ios-build" ghost @click="showCatTreeModal()">选择分类</Button>
    <i-col v-for="(item,index) in categories">
      <span style="text-align: left;font-size: 0.5em" v-if="index<20||isShowAll">{{item.level1}} /{{item.level2}}/{{item.level3}}</span>
    </i-col>
    <div style="width: 100%;text-align: right;padding-right:9rem" v-if="categories.length>20">
      <Button type="dashed" size="small" @click="isShowAll=!isShowAll">{{isShowAll?'点我折叠全部分类......':'点我查看分类列表......'}}</Button>
    </div>

    <!-- 选择分类弹窗 -->
    <Modal v-model="isShowCatTree" footer-hide :width="400">
      <Tree :data="categoryTree" show-checkbox :multiple="true" style="text-align: left;"
            ref="catTree" @on-toggle-expand="toggleExpand"  @on-check-change="changeCategories"></Tree>
    </Modal>
  </div>
</template>

<script>
import {createCategoryTree} from "./js/categoryFuns";
import {getProductCommonData} from "../../js/commonUtils";

export default {
  name: "CategoryTree",
  props: {
    selectedCategories: {type: Array, default() {return []}},
  },
  model: {
    prop: "selectedCategories",
    event: "change"
  },
  data() {
    return {
      categoryTree: [],
      isShowAll: false,
      isShowCatTree: false,
    }
  },
  methods: {
    showCatTreeModal() {
      this.isShowCatTree = true;
    },
    hideCatTreeModal() {
      this.isShowCatTree = false;
    },
    createCategoryTree(self, categoryTree) {
      createCategoryTree(self, categoryTree, this.selectedCategories);
    },
    toggleExpand(data) {
      //展开分类，关闭同一级分类
      let self = this;
      if(data.expand && data.level==1){
        self.categoryTree.forEach(function(item, index){
          if(data.value!=item.value&&item.expand==true){
            item.expand=false;
            self.categoryTree.splice(index,1,item)
          }
        });
      }
    },
    changeCategories() {
      let categories = [];
      this.$refs.catTree.getCheckedNodes().forEach(function(item){
        if(item.level==3) {
          categories.push(item.value);
        }
      });
      this.selectedCategories.splice(0);
      this.selectedCategories.push(...categories);
    },
  },
  computed: {
    categories() {
      let self = this;
      let categories = [];
      self.categoryTree.forEach((item1)=>{
        item1.children.forEach((item2)=>{
          item2.children.forEach((item3)=>{//3级分类选中
            if(self.selectedCategories.includes(item3.value)){
              categories.push({'level1': item1.title, level2: item2.title, level3: item3.title});
            }
          });
        });
      });
      return categories;
    },
  },
  mounted() {
    getProductCommonData(this, this.categoryTree, [3], false, this.createCategoryTree);
  },
  watch: {
    "selectedCategories": {
      handler() {
        this.createCategoryTree(this, this.categoryTree, this.selectedCategories);
      },
    }
  }
}
</script>

<style scoped>

</style>
